<?php

namespace app\index\controller;

use app\common\model\Klass;
use app\common\model\Teacher;
use think\Request;

class KlassController extends IndexController
{
    public function index()
    {
        $klasses = Klass::paginate();
        $this->assign('klasses', $klasses);
        return $this->fetch();
    }

    public function add()
    {
        //获取所有的教师信息
        $teachers = Teacher::all();
        $this->assign('teachers', $teachers);
        return $this->fetch();
    }

    public function save()
    {
        var_dump(Request::instance()->post());
        //实例化班级并赋值
        $Klass = new Klass();
        $Klass->name = Request::instance()->post('name');
        $Klass->teacher_id = Request::instance()->post('teacher_id/d');
        //添加数据,注意需要使用allowField，并且在save中传入对象，否则会报错
        if (!$Klass->validate(true)->allowField(true)->save($Klass)) {
            return $this->error('数据添加错误：' . $Klass->getError());
        }

        return $this->success('操作成功', url('index'));
    }

    public function edit()
    {
        $id = Request::instance()->param('id/d');

        //获取所有的教师信息
        $teachers = Teacher::all();
        $this->assign('teachers', $teachers);

        //获取用户操作的班级信息
        if (false === $Klass = Klass::get($id)) {
            return $this->error('系统未找到ID为' . $id . '的记录');
        }
        $this->assign('Klass', $Klass);
        return $this->fetch();
    }

    public function update()
    {
        $id = Request::instance()->post('id/d');

        //获取传入的班级信息
        $Klass = Klass::get($id);
        if (is_null($Klass)) {
            return $this->error('系统未找到ID为' . $id . '的记录');
        }

        //数据更新
        $Klass->name = Request::instance()->post('name');
        $Klass->teacher_id = Request::instance()->post('teacher_id/id');
        if (!$Klass->validate()->save()) {
            return $this->error('更新错误：' . $Klass->getError());
        } else {
            return $this->success('操作成功', url('index'));
        }
    }


    public function delete()
    {
        //接收参数
        $id = Request::instance()->param('id');
        //var_dump($id);
        // 获取要删除的对象
        $Klass = Klass::get($id);
        //删除操作
        if (!is_null($Klass)) {
            $Klass->delete();
            return $this->success('删除成功', url('index'));
        } else {
            return $this->error('待删除的对象不存在');
        }
    }
}